<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" width="1120px">
    <a-form ref="formRef" :model="formData" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="validatorRules">
      <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">委托单位信息</h4>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="委托单位" name="entName">
            <!-- <j-dict-select-tag v-model:value="formData.entName" dictCode="lab_enterprise,ent_name,ent_name"
              :disabled="disabled" /> -->
              <a-input v-model:value="formData.entName" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="单位地址" name="entAddress">
            <a-input v-model:value="formData.entAddress" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="经办人" name="handler">
            <a-input v-model:value="formData.handler" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="经办日期" name="handlDate">
            <a-date-picker valueFormat="YYYY-MM-DD" v-model:value="formData.handlDate" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系人" name="contacter">
            <a-input v-model:value="formData.contacter" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="联系电话" name="phone">
            <a-input v-model:value="formData.phone" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">委托样品信息</h4>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="取/送样" name="takeSendSample">
            <j-dict-select-tag v-model:value="formData.takeSendSample" dictCode="take_send" :show-choose-option="false"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品大类" name="sampleTypeId">
            <a-input style="display:none" v-model:value="formData.sampleType"></a-input>
            <j-dict-select-tag v-model:value="formData.sampleTypeId" dictCode="lab_items,name,id,type='A'"
              :show-choose-option="false" :disabled="disabled" @change="handleTypeChange" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品类别" name="sampleSort">
            <a-input style="display:none" v-model:value="formData.sampleSort" :disabled="disabled"></a-input>
            <!--循环加载样品类别下拉选项 -->
            <a-select v-model:value="formData.sampleSortId" style="width: 100%" :disabled="disabled"  @change="handleSortChange">
              <a-select-option v-for="sort in formData.sortsList" key="{{sort.id}}" :value="sort.id.toString()"
                :label="sort.name">
                {{ sort.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="8">
          <a-form-item label="样品存储说明" v-bind="validateInfos.sampleStoreRemark">
            <a-input v-model:value="formData.sampleStoreRemark"  :disabled="disabled"></a-input>
          </a-form-item>
        </a-col> -->
        <a-col :span="8">
          <a-form-item label="样品名称" name="sampleName">
            <a-input v-model:value="formData.sampleName" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品数量" name="sampleNum">
            <a-input-number v-model:value="formData.sampleNum"  style="width: 100%" :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品包装" name="samplePack">
            <a-input v-model:value="formData.samplePack" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品存储" name="sampleStore">
            <j-dict-select-tag v-model:value="formData.sampleStore" dictCode="sample_store" :show-choose-option="false"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="样品处置" name="sampleDispose">
            <j-dict-select-tag v-model:value="formData.sampleDispose" dictCode="sample_dispose"
              :show-choose-option="false" :disabled="disabled" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-divider type="vertical" class="antd-modal-divider" />
        <h4 class="hClass">检测项目信息</h4>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-item label="检测项目" name="testItems">
            <a-select v-model:value="formData.AtestItems" mode="multiple" style="display:none"></a-select>
            <a-select v-model:value="formData.AtestItemsIds" mode="multiple" :options="options"></a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="方法/标准" name="wayNorm">
            <j-dict-select-tag v-model:value="formData.wayNorm" dictCode="way_norm" :show-choose-option="false"
              :disabled="disabled" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-tabs style="margin-bottom: 3px;">
        <a-tab-pane tab="样品信息">
          <div style="margin-bottom: 3px;">
            <a-row type="flex" style="margin-bottom: 3px;">
              <a-col :span="3" style="text-align: center;">样品编号</a-col>
              <a-col :span="4" style="text-align: center;">样品名称</a-col>
              <a-col :span="2" style="text-align: center;">规格型号</a-col>
              <a-col :span="2" style="text-align: center;">产品批号</a-col>
              <a-col :span="3" style="text-align: center;">取样日期</a-col>
              <a-col :span="2" style="text-align: center;">样品量</a-col>
              <a-col :span="3" style="text-align: center;">样品外观</a-col>
              <a-col :span="3" style="text-align: center;">其他说明</a-col>
              <a-col :span="2" style="text-align: center;">操作</a-col>
            </a-row>
            <a-row type="flex" style="margin-bottom: 3px;height: 30px;" gutter="1px"
              v-for="(item, index) in formData.labSampleList" :key="index">
              <a-col :span="2" style="display: none">
                <a-form-item>
                  <a-input placeholder="id" v-model:value="item.id" />
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item>
                  <a-input v-model:value="item.samNum" style="width: 134px;" :disabled="disabled" />
                </a-form-item>
              </a-col>
              <a-col :span="4">
                <a-form-item>
                  <a-input v-model:value="item.samName" style="width: 178px;" :disabled="disabled" />
                </a-form-item>
              </a-col>
              <a-col :span="2">
                <a-form-item>
                  <a-input v-model:value="item.model" style="width: 87px;" :disabled="disabled" />
                </a-form-item>
              </a-col>
              <a-col :span="2">
                <a-form-item>
                  <a-input v-model:value="item.lotNum" style="width: 90px;" :disabled="disabled" />
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item>
                  <a-date-picker valueFormat="YYYY-MM-DD" v-model:value="item.samDate" style="max-width: 125px;"
                    :disabled="disabled" />
                </a-form-item>
              </a-col>
              <a-col :span="2">
                <a-form-item>
                  <a-input v-model:value="item.samQuality" style="width: 88px;" :disabled="disabled" />
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item>
                  <a-input v-model:value="item.samAppear" style="width: 130px;" :disabled="disabled" />
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item>
                  <a-input v-model:value="item.remark" style="width: 130px;" :disabled="disabled" />
                </a-form-item>
              </a-col>
              <a-col :span="2">
                <a-form-item>
                  <Icon icon="ant-design:minus-outlined" @click="delRowCustom(index)"
                    style="fontsize: 20px;width: 85px;" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-button type="dashed" style="width: 98%; margin-top: 10px;" @click="addRowCustom" :disabled="disabled">
              <Icon icon="ph:plus-bold" />
              添加样品信息
            </a-button>
          </div>
        </a-tab-pane>
      </a-tabs>
      <a-row>
        <a-col :span="8">
          <a-form-item label="配样" name="samPrep">
            <a-input v-model:value="formData.samPrep" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label="配方" name="samForm">
            <a-input v-model:value="formData.samForm"
              style="width: 600px; border-radius: 4px 4px 4px 4px;  opacity: 1;  border: 0.5px solid #DDDDDD;"
              :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <div v-show="formData.showDivA">
        <a-row>
          <a-divider type="vertical" class="antd-modal-divider" />
          <h4 class="hClass">结果报告</h4>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-item label="报告编号" name="reportCode">
              <a-input v-model:value="formData.reportCode" :disabled="disabled"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="报告类型" name="reportType">
              <j-dict-select-tag v-model:value="formData.reportType" dictCode="report_type" :show-choose-option="false"
                :disabled="disabled" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="交付时间" name="deliverData">
              <a-date-picker v-model:value="formData.deliverData" value-format="YYYY-MM-DD" style="width: 100%"
                :disabled="disabled" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="报告数量" name="reportNum">
              <a-input-number v-model:value="formData.reportNum" style="width: 100%" :disabled="disabled" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="交付方式" name="deliverWay">
              <j-dict-select-tag v-model:value="formData.deliverWay" dictCode="deliver_way" :show-choose-option="false"
                :disabled="disabled" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-divider type="vertical" class="antd-modal-divider" />
          <h4 class="hClass">检验费用</h4>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-item label="检验费" name="checkCost">
              <a-input-number v-model:value="formData.checkCost" style="width: 100%" :disabled="disabled" />
            </a-form-item>
          </a-col>
          <span>(付费方式：转账或存到检验单位指定账户（见收费通知），到账后开展检验工作。)</span>
        </a-row>
        <a-row>
          <a-divider type="vertical" class="antd-modal-divider" />
          <h4 class="hClass">分包信息</h4>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-item label="分包项目" name="subItems">
              <a-input v-model:value="formData.subItems" :disabled="disabled"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="分包机构" name="subOrg">
              <a-input v-model:value="formData.subOrg" :disabled="disabled"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="是否征求同意" :label-col="{span:6}" :wrapper-col="{span:5}" name="seekMark">
              <j-dict-select-tag v-model:value="formData.seekMark" dictCode="yn" :show-choose-option="true" 
                :disabled="disabled" />
            </a-form-item>
          </a-col>
        </a-row>
      </div>
    </a-form>
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface';
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import JSelectMultiple from '/@/components/Form/src/jeecg/components/JSelectMultiple.vue';
// import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
import { saveOrUpdate, labSampleList, labSortsList } from '../LabEntrust.api';
import { SelectProps } from 'ant-design-vue';


export default defineComponent({
  name: 'tableModal',
  components: { BasicModal, JDictSelectTag, JSelectMultiple },
  emits: ['success', 'register'],
  setup(props, { emit }) {
    const isUpdate = ref(true);
    const rowId = ref('');
    const formRef = ref();
    const disabled = ref(false);
    const options = ref<SelectProps['options']>([]);
    const labelCol = reactive({
      xs: { span: 24 },
      sm: { span: 5 },
    });
    const wrapperCol = reactive({
      xs: { span: 24 },
      sm: { span: 16 },
    });
    const validatorRules = {

    };
    const formData = reactive({
      id: null,
      entName: '',
      entAddress: '',
      handler: '',
      handlDate: null,
      contacter: '',
      phone: '',
      takeSendSample: '',
      sampleTypeId: '',
      sampleType: '',
      sampleSortId: '',
      sampleSort: '',
      sampleName: '',
      sampleNum: '',
      samplePack: '',
      sampleStore: '',
      sampleDispose: '',
      testItemsIds: '',
      testItems: '',
      wayNorm: '',
      remark: '',
      conAtta: '',
      auditMark: '制单中',
      labSampleList: [],
      samPrep: '',
      samForm: '',
      reportCode: '',
      reportType: '',
      deliverData: '',
      reportNum: '',
      deliverWay: '',
      checkCost: '',
      subItems: '',
      subOrg: '',
      seekMark: '',
      showDivA: false,
      sortsList: [],
      itemsList: [],
      AtestItemsIds: [],
      AtestItems: [],
    });
    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      setModalProps({ confirmLoading: false, showOkBtn: !data.disabled });
      isUpdate.value = !!data?.isUpdate;
      disabled.value = data.disabled;
      reset();
      if (unref(isUpdate.value)) {
        rowId.value = data.record.id;
        Object.assign(formData, data.record);
        let params = { id: formData.id };
        const customerList = await labSampleList(params);
        formData.labSampleList = customerList;
        //编辑或查看进入页面样品大类不为空时，加载样品类型下拉数据
        if (formData.sampleTypeId != null || formData.sampleTypeId != "") {
          formData.sortsList = (await labSortsList({ id: formData.sampleTypeId })).records;
        }
        //编辑或查看进入页面样品类型不为空时，加载实验项目下拉数据
        if (formData.sampleSortId != null || formData.sampleSortId != "") {
          //加载实验项目
          loadItems();
        }
        //编辑或查看进入页面加载实验项目下拉数据,并把已有的数据转换成数组
        if (formData.testItemsIds != null || formData.testItemsIds != "") {
          // 将JSON字符串对象转换为对象数组
          formData.AtestItemsIds = JSON.parse(formData.testItemsIds);
          // formData.AtestItems = JSON.parse(formData.testItems);

        }
      }
    });
    const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

    //动态添加行
    function addRowCustom() {
      formData.labSampleList.push({});
    }

    //删除行
    function delRowCustom(index) {
      formData['labSampleList'].splice(index, 1);
      formData.labSampleList.splice(index, 1);
    }
    function reset() {
      formData.id = null;
      formData.entName = '';
      formData.entAddress = '';
      formData.handler = '';
      formData.handlDate = null;
      formData.contacter = '';
      formData.phone = '';
      formData.takeSendSample = '';
      formData.sampleTypeId = '';
      formData.sampleType = '';
      formData.sampleSortId = '';
      formData.sampleSort = '';
      formData.sampleName = '';
      formData.sampleNum = '';
      formData.samplePack = '';
      formData.sampleStore = '';
      formData.sampleDispose = '';
      formData.testItemsIds = '';
      formData.testItems = '';
      formData.wayNorm = '';
      formData.remark = '';
      formData.conAtta = '';
      formData.auditMark = '制单中';
      formData.labSampleList = [];
      formData.samPrep = '';
      formData.samForm = '';
      formData.reportCode = '';
      formData.reportType = '';
      formData.deliverData = '';
      formData.reportNum = '';
      formData.deliverWay = '';
      formData.checkCost = '';
      formData.subItems = '';
      formData.subOrg = '';
      formData.seekMark = '';
      formData.showDivA = false;
      formData.sortsList = [];
      formData.itemsList = [];
      formData.AtestItemsIds = [];
      formData.AtestItems = [];
    }

    //样品大类改变时加载样品类型下拉数据
    async function handleTypeChange() {
      const typeId = formData.sampleTypeId;
      let params = { id: typeId };

      //如果样品类型已有选中的数据先清空已选中的数据
      handleClearSort();
      //如果实验项目已有选中的数据先清空已选中的数据
      handleClearItems();
      //清空样品类型下拉数据
      formData.sortsList = [];
      //重新给样品类型下拉赋值
      formData.sortsList = (await labSortsList(params)).records;
    }


    //样品类别类改变时
    async function handleSortChange() {
      //如果实验项目已有选中的数据先清空已选中的数据
      handleClearItems();
      //重新加载实验项目
      loadItems();
    }
    //加载实验项目
    async function loadItems() {
      const SortId = formData.sampleSortId;
      let params = { id: SortId };
      //清空实验项目下拉数据
      formData.itemsList = [];
      //重新给实验项目下拉框赋值
      formData.itemsList = (await labSortsList(params)).records;
      options.value = [];
      for (let i = 0; i < formData.itemsList.length; i++) {
        options.value.push({
          label: formData.itemsList[i].name,
          value: formData.itemsList[i].id,
        });
      }
    }
    //清空已选中的样品类型数据
    function handleClearSort() {
      if (formData.sampleSortId != null || formData.sampleSortId != '') {
        formData.sampleSortId = '';
        formData.sampleSort = '';
      }
    }
    //清空已选中的实验项目数据
    function handleClearItems() {
      if (formData.AtestItemsIds != null || formData.AtestItemsIds != '') {
        formData.AtestItemsIds = [];
        formData.AtestItems = [];
        formData.testItems = '';
        formData.testItemsIds = '';
      }
    }
    //把选中的实验项目由数组转成JSON字符串
    function itemsArrayToJson() {
      if (formData.AtestItems != null || formData.AtestItems != "") {
        formData.testItems = JSON.stringify(formData.AtestItems);
        formData.testItemsIds = JSON.stringify(formData.AtestItemsIds);
      }

    }
    //提交表单数据
    async function handleSubmit() {
      formRef.value
        .validate()
        .then(async () => {
          try {
            itemsArrayToJson();
            setModalProps({ confirmLoading: true });
            await saveOrUpdate(formData, unref(isUpdate));
            closeModal();
            emit('success');
          } finally {
            setModalProps({ confirmLoading: false });
          }
        })
        .catch((error: ValidateErrorEntity<any>) => {
          console.log('error', error);
        });
    }

    return {
      formRef,
      validatorRules,
      formData,
      getTitle,
      labelCol,
      wrapperCol,
      disabled,
      options,
      registerModal,
      addRowCustom,
      delRowCustom,
      handleSubmit,
      handleTypeChange,
      handleSortChange,
      handleClearSort,
      loadItems,
      handleClearItems,
      itemsArrayToJson,
    };
  },
});
</script>
<style  lang="less" scoped>
.ant-btn {
  padding: 0 10px;
  margin-left: 3px;
}

.ant-form-item-control {
  line-height: 0px;
}

/** 主表单行间距 */
.ant-form .ant-form-item {
  margin-bottom: 10px;
}

/** Tab页面行间距 */
.ant-tabs-content .ant-form-item {
  margin-bottom: 0px;
}


.hClass {
  width: 160px;
  height: 20px;
  font-size: 14px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 550;
  color: #009688;
  line-height: 14px;
}

.ant-form-item-label {
  width: 150px;
  height: 20px;
  font-size: 14px;
  font-family: Microsoft YaHei-Regular, Microsoft YaHei;
  font-weight: 400;
  color: #727272;
  line-height: 20px;
}

.ant-input {
  width: 220px;
  height: 32px;
  border-radius: 4px 4px 4px 4px;
  opacity: 1;
  border: 1px solid #DDDDDD;
}

.ant-picker {
  width: 220px !important;
  height: 32px;
  border-radius: 4px 4px 4px 4px;
  opacity: 1;
  border: 1px solid #DDDDDD;
}


:deep(.ant-form-item-control-input) {
  width: 220px !important;
}

:deep(.ant-tabs-content-holder) {
  border-bottom: 1px solid #DDDDDD;
}
</style>

